package auth

import (
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/app-starter/server"
	"github.com/lishimeng/app-starter/token"
	"github.com/lishimeng/go-log"
	"github.com/lishimeng/x/container"
)

type PasswordLoginReq struct {
	UserName string `json:"userName"`
	Password string `json:"password"`
}

type LoginResp struct {
	Token        string `json:"token,omitempty"`
	RefreshToken string `json:"refresh_token,omitempty"`
}

func passwordLogin(ctx server.Context) {

	log.Info("login password")
	var req PasswordLoginReq

	var resp app.ResponseWrapper

	var err error

	err = ctx.C.ReadJSON(&req)
	if err != nil {
		log.Info(err)
		resp.Code = 500
		ctx.Json(resp)
		return
	}

	var tokenPayload token.JwtPayload
	tokenPayload.Uid = "1234455"
	tokenPayload.Client = "pc"

	tokenStr, err := genToken(tokenPayload)
	if err != nil {
		log.Info(err)
		resp.Code = 500
		ctx.Json(resp)
		return
	}

	resp.Code = 200
	resp.Data = LoginResp{
		Token:        string(tokenStr),
		RefreshToken: tokenPayload.Uid + string(tokenStr),
	}
	ctx.Json(resp)
}

func genToken(payload token.JwtPayload) (content []byte, err error) {
	var provider token.JwtProvider
	err = container.Get(&provider)
	if err != nil {
		return
	}
	log.Info("tokenPayload: %s", payload)
	content, err = provider.Gen(payload)
	return
}
